<?php
// +----------------------------------------------------------------------
// | 用户已购项目
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;

class UserYgProj extends Model
{
	
	//商品，一对一关联
	public function num(){
        return $this->hasMany('UserYgProj','goods_id','goods_id');
    }
    
		
	//商品，一对一关联
	public function goods(){
        return $this->hasOne('goods','id','goods_id')->bind([
        	'goods_name'=>'name',
        	'goods_img'=>'img',
        ]);
    }
    
    //商品规格，一对一关联
	public function specs(){
        return $this->hasOne('goodsSpecs','id','specs_id')->bind([
        	'specs_name'=>'name',
        	'specs_img'=>'img',
        ]);
    }
		
		
	//获取已购项目
	public function getYgProj($uid,$shop_id=-1){
      	$model = self::with(['goods','specs'])->alias('a')
      		->leftJoin('user b','a.uid = b.id')
      		->leftJoin('shop c','c.id = a.shop_id')
      		->field('a.*')
      		->field('c.name as shop_name')
      		->where('a.meal_id','<',1)
      		->where('a.uid',$uid)
      		//->where('a.shop_id',$shopId)
      		->order('a.use_num');
          if($shop_id!=-1)	$model->where('a.shop_id',$shop_id);
		$data = $model->all();
				
		$datas = [];
		$specs_ids = [];
		foreach($data as $key => $value){
			if( !in_array($value['specs_id'], $specs_ids) ){
				$specs_ids[] = $value['specs_id'];
				$value['num_count'] = self::where('specs_id', $value['specs_id'])
					->where('uid',$uid)
					->where('meal_id','<',1)
					->field('(sum(num) - sum(use_num)) as num_count')
					->find()['num_count'];
				$datas[] = $value;
			}
		}
		
		return 	$datas;
    }	
    
}
